<?php

namespace Reezy\OAuth\Driver;


use Reezy\OAuth\OAuthBase;
use Reezy\OAuth\OAuthInfo;

/**
 * @see http://open.douyin.com/platform
 */
class OAuthDouyin extends OAuthBase
{

    const BASE_URL = 'https://open.douyin.com';

    const SILENT_CODE_URL = 'https://aweme.snssdk.com/oauth/authorize/v2/';

    protected $scope = 'login_id';

    public function isSupportSilentMode(): bool
    {
        return $this->scope === 'login_id';
    }

    public function getAuthUrl(string $redirectUri = null, string $state = null, bool $isSilent = false): string
    {
        $url = $isSilent ? self::SILENT_CODE_URL : (self::BASE_URL . '/platform/oauth/connect');
        return self::buildUrl($url, [
            'client_key' => $this->clientId,
            'redirect_uri' => $redirectUri ?? $this->redirectUri,
            'scope' => $isSilent ? $this->scope : 'user_info',
            'state' => $state,
            'response_type' => 'code',
        ]);
    }

    public function getAccessToken(string $code): OAuthInfo
    {
        $response = $this->httpGet(self::BASE_URL . '/oauth/access_token', [
            'client_key' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code' => $code,
            'grant_type' => 'authorization_code',
        ]);
        return OAuthInfo::token($response['data']);
    }


    public function getUserInfo(OAuthInfo $token): OAuthInfo
    {
        $token->checkOpenId();

        $response = $this->httpGet(self::BASE_URL . '/oauth/userinfo/', [
            'access_token' => $token->getAccessToken(),
            'open_id' => $token->getOpenId(),
        ]);

        $info = $response['data'];

        return OAuthInfo::userinfo($info, 'nickname', 'avatar');
    }
}
